package com.frogs.ucenter.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;
import org.jsoup.Connection.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.PageTurn;
import com.frogs.system.util.ApiUrlParamEnum;
import com.frogs.system.web.api.entity.ApiUrl;
import com.frogs.system.web.api.response.Response.ApiResultEnum;
import com.frogs.system.web.api.response.Response.ResultParamEnum;
import com.frogs.ucenter.entity.UserIntegralBalance;
import com.frogs.ucenter.service.AbsService;
import com.frogs.ucenter.service.UserIntegralService;

@Service("userIntegralService")
public class UserIntegralServiceImpl extends AbsService implements UserIntegralService {
	
	private static Logger log = LoggerFactory.getLogger(UserIntegralServiceImpl.class);
	

	/**
	 * 获取用户积分
	 */
	@Override
	public UserIntegralBalance getUserIntegralInfo(Integer userId)
			throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_INTEGRAL_BALANCE_SHOW");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(),
				 };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		JSONObject result = null;
		UserIntegralBalance userIntegralBalance = null;
		try{
			result = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == result.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				userIntegralBalance = result.getJSONObject("response").getObject("info", UserIntegralBalance.class);
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserIntegralInfo] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取用户积分接口请求失败！");
		}
		
		return userIntegralBalance;
	}

	/**
	 * 获取用户积分消费列表
	 */
	@Override
	public PageList<Map<String,Object>> getUserIntegralConsumeRecordList(Integer userId, Integer pageNo, Integer pageSize)
			throws Exception {
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(), 
				
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString() };
		return this.getConsumeRecordList(otherParams,"USER_INTEGRAL_CONSUME_RECORD_LIST");
	}
	
	/**
	 * 获取所有积分消费列表
	 */
	@Override
	public PageList<Map<String,Object>> getIntegralConsumeRecordList( Integer pageNo, Integer pageSize)
			throws Exception {
		
		String[] otherParams = {
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString() };
		return this.getConsumeRecordList(otherParams,"INTEGRAL_CONSUME_RECORD_LIST");
	}
	
	private PageList<Map<String,Object>> getConsumeRecordList(String[] otherParams,String urlKey) throws Exception{
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl(urlKey);
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);

		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				List<Map<String, Object>> list = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
				result.addAll(list);
				
		    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
		    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserIntegralConsumeRecordList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取用户积分消费记录接口请求失败！");
		}
		
		return result;
	}

	/**
	 * 获取用户积分记录
	 */
	@Override
	public PageList<Map<String,Object>> getUserIntegralRecordList(Integer userId,
			Integer pageNo, Integer pageSize) throws Exception {
		ApiUrl apiUrl = this.buildUcenterApiBaseUrl("USER_INTEGRAL_RECORD_LIST");
		String[] otherParams = {ApiUrlParamEnum.userId.getParamName(), userId.toString(), 
				
				ApiUrlParamEnum.pageNo.getParamName(), pageNo.toString(),
				ApiUrlParamEnum.pageSize.getParamName(), pageSize.toString() };
		String[] allParams = (String[])ArrayUtils.addAll(apiUrl.getKeyvals(), otherParams);
		
		PageList<Map<String,Object>> result = new PageList<Map<String,Object>>();
		JSONObject jsonObjectResult = null;
		try{
			jsonObjectResult = (JSONObject)this.requestApi(apiUrl.getUrl(), Method.POST, allParams);
			if (ApiResultEnum.SUCCESS.getId() == jsonObjectResult.getJSONObject("response").getIntValue(ResultParamEnum.code.getParamName())) {
				List<Map<String, Object>> list = jsonObjectResult.getJSONObject("response").getObject("list", List.class);
				result.addAll(list);
				
		    	JSONObject pageTurnJSONObject = jsonObjectResult.getJSONObject("response").getJSONObject("pageTurn");
		    	result.setPageTurn(JSON.toJavaObject(pageTurnJSONObject, PageTurn.class));
			}
		} catch (IllegalStateException e) {
			log.error("func[getUserIntegralRecordList] url[{}] params[{}] exception[{} - {}] desc[fail]",
					new Object[] { apiUrl.getUrl(),Arrays.deepToString(allParams), e.getMessage(), Arrays.deepToString(e.getStackTrace()) });
		} catch(Exception e){
			throw new Exception("获取用户积分记录接口请求失败！");
		}
		
		return result;
	}
}
